package com.gxuwz.zhangjiahui.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.zhangjiahui.entity.*;
import com.gxuwz.zhangjiahui.service.*;
import com.gxuwz.zhangjiahui.service.IConclusionService;
import org.apache.ibatis.annotations.Param;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhangjiahui
 * @since 2021-06-20
 */
@Controller
@RequestMapping("/conclusion")
public class ConclusionController {

    @Autowired
    private IConclusionService iConclusionService;
    @Autowired
    private IProjectService iProjectService;
    @Autowired
    private IEnclosureService iEnclosureService;


    /**
     * 查询全部信息
     * @param modelAndView
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @Pointcut
    @ResponseBody
    @RequestMapping(value = "/findConclusion")
    public ModelAndView findConclusion(ModelAndView modelAndView, Page page, Integer pageNumber, Conclusion Conclusion,
                                    @Param("conclusionId") String conclusionId,
                                    HttpServletRequest request, HttpServletResponse response) {
        if(request.getSession().getAttribute("nowResult") != null){
            if (!request.getSession().getAttribute("nowResult").equals("now")) {
                request.getSession().setAttribute("result", "");
            }
            request.getSession().setAttribute("nowResult", "");
        }
        // 可以通过 wrapper 进行筛选!!!
        QueryWrapper<Conclusion> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("conclusion_id");
        // 进行模糊查询!!!
        if(conclusionId != null && conclusionId != ""){
            wrapper.like("conclusion_id", conclusionId);
            request.getSession().setAttribute("conclusionId", conclusionId);
        }else {
            request.getSession().setAttribute("conclusionId", "");
        }
        // 指导老师只能看到自己指导的项目 findProjectByStuNoOrTeamId
        if(request.getSession().getAttribute("instructorNow") != null){
            // 查询该指导老师指导的项目
            Project project = new Project();
            project.setProjectId((String) request.getSession().getAttribute("instructorNow"));
            List<Project> projectList = iProjectService.findProjectByStuNoOrTeamId(project);
            if(projectList != null){
                for(Project project1: projectList){
                    // and ( a or b )： 语法: wrapper.and(i -> i.eq().or().eq())
                    wrapper.eq("project_id", project1.getProjectId()).or();
                }
            }
        }
        // Current,页码 + Size,每页条数
        if(pageNumber == null){
            page.setCurrent(1);
        }else {
            page.setCurrent((long)pageNumber);
        }
        // 默认每页6行数据！
        page.setSize(6);
        // 调用分页查询方法！!
        IPage<Conclusion> conclusionIPage = iConclusionService.selectConclusionPage(page, wrapper);
        // 存放page，内有当前页数
        modelAndView.addObject("page", page);
        System.out.println("总条数"+conclusionIPage.getTotal());
        System.out.println("总页数"+conclusionIPage.getPages());
        // 存放总页数
        modelAndView.addObject("pages", (int)conclusionIPage.getPages());
        // 存放一个数组用来让foreach遍历
        int[] pagesList = new int[(int)conclusionIPage.getPages()];
        for(int i=0; i< (int)conclusionIPage.getPages(); i++){
            pagesList[i] = i+1;
        }
        modelAndView.addObject("pagesList", pagesList);
        modelAndView.addObject("numberPages", conclusionIPage.getTotal());
        List<Conclusion> conclusionList = conclusionIPage.getRecords();
        System.out.println("conclusionList = "+conclusionList);
        modelAndView.addObject("conclusionList", conclusionList);

        modelAndView.setViewName("conclusion/conclusion_list");

        return modelAndView;
    }



    /**
     * 添加/修改 信息
     * @param conclusion
     * @return
     */
    @RequestMapping(value = "/addEditConclusion")
    public ModelAndView addEditConclusion(Conclusion conclusion,
                                          @Param("keyNow") Integer keyNow,
                                          @Param("approvalStateText") String approvalStateText,
                                          @RequestParam("file") MultipartFile file,
                                          HttpServletRequest request, ModelAndView modelAndView) throws IOException {
        Conclusion conclusion1 = iConclusionService.findConclusionById(conclusion);
        System.out.println("conclusion = " + conclusion);
        System.out.println("conclusion1 = " + conclusion1);
        // 新增信息
        if(conclusion1 == null){
            System.out.println("进入新增");
            iConclusionService.addConclusion(conclusion);
            if(file != null){ // 附件上传，新增附件内容
                // 上传附件内容
                if(file.isEmpty()){
                    System.out.println("上传失败！,请选择文件夹");
                }
                String fileName = "结题文件-" + file.getOriginalFilename();
                String pathNow = "\\src\\main\\resources\\static\\file\\";
                String filePath = System.getProperty("user.dir") + pathNow;
                File dest = new File(filePath + fileName);
                file.transferTo(dest);

                // 新增附件信息
                Enclosure enclosure = new Enclosure();
                // 新增
                String timestamp = String.valueOf(new Date().getTime());
                String mun = (int) (Math.random()*900 + 100) + "";
                System.out.println("FJ" + timestamp + mun);
                enclosure.setEnclosureId("FJ" + timestamp + mun);

                enclosure.setProjectId(conclusion.getProjectId());
                enclosure.setEnclosureName(fileName);
                enclosure.setEnclosureUrl("/file/");

                iEnclosureService.addEnclosure(enclosure);

            }
        }
        // 修改用户信息
        if(conclusion1 != null){
            if(keyNow != null && keyNow == 1){ // 审批通过
                conclusion1.setApprovalStateOne(1);
                conclusion1.setEvaluateStateOne("通过");
                // 修改对应项目的获奖情况
                Project project = new Project();
                project.setProjectId(conclusion1.getProjectId());
                project = iProjectService.findProjectById(project);
                if(project != null){
                    project.setKeyState(1);
                    iProjectService.updateProjectById(project);
                }
                try {
                    iConclusionService.updateConclusionById(conclusion1);
                    request.getSession().setAttribute("result", "editTrue");
                    request.getSession().setAttribute("nowResult", "now");
                }catch (Exception e){
                    request.getSession().setAttribute("result", "editFalse");
                    request.getSession().setAttribute("nowResult", "now");
                }
            }else if(approvalStateText != null){ // 拒批
                System.out.println("进入审批");
                conclusion1.setApprovalStateOne(2);
                conclusion1.setEvaluateStateOne(approvalStateText);
                try {
                    iConclusionService.updateConclusionById(conclusion1);
                    request.getSession().setAttribute("result", "editTrue");
                    request.getSession().setAttribute("nowResult", "now");
                }catch (Exception e){
                    request.getSession().setAttribute("result", "editFalse");
                    request.getSession().setAttribute("nowResult", "now");
                }
            }else {
                System.out.println("进入修改");
                try {
                    iConclusionService.updateConclusionById(conclusion);
                    request.getSession().setAttribute("result", "editTrue");
                    request.getSession().setAttribute("nowResult", "now");
                }catch (Exception e){
                    request.getSession().setAttribute("result", "editFalse");
                    request.getSession().setAttribute("nowResult", "now");
                }
            }
        }
        modelAndView.setViewName("redirect:/conclusion/findConclusion");
        return modelAndView;
    }



    /**
     * 删除信息
     * @param conclusionId
     * @return
     */
    @GetMapping(value = "/deleteConclusion")
    public ModelAndView deleteConclusion(HttpServletRequest request, ModelAndView modelAndView,
                             @Param("conclusionId") String conclusionId) {
        Conclusion conclusion = new Conclusion();
        conclusion.setConclusionId(conclusionId);
        try {
            iConclusionService.deleteConclusionById(conclusion);
            request.getSession().setAttribute("result", "deleteTrue");
            request.getSession().setAttribute("nowResult", "now");
        }catch (Exception e){

        }
        modelAndView.setViewName("redirect:/conclusion/findConclusion");
        return modelAndView;
    }

}
